﻿using UnityEngine;
using System.Collections;
using Dict.DataModel;

namespace Room
{

    public class RCAIPet : RCAIBase
    {
        public TablePet tablePet;
        public RoomCharactor master;
        public float maxDis;

        public enum State
        {
            Stand,
            Move,
        }

        public State state = State.Stand;

        public RCAIPet(RoomCharactor owner)
            : base(owner)
        {
            type = AIType.Pet;
        }

        public void Init(TablePet tablePet, RoomCharactor master)
        {
            this.tablePet = tablePet;
            this.master = master;
            maxDis = (float)Dict.DictDataManager.Instance.tableGameConfigureDao.currentData.PetMaxDistanceFromMaster;

            var randomPos = Random.insideUnitSphere * maxDis;
            var rPos = new Vector3(
                randomPos.x + master.transform.position.x, 
                master.transform.position.y, 
                randomPos.z + master.transform.position.z
                );
            owner.gameObject.SetActive(false);
            owner.gameObject.transform.position = rPos;
            owner.gameObject.SetActive(true);
        }

        public override void Tick()
        {
            CheckNeedMove();
        }

        void CheckNeedMove()
        {
            if (master != null)
            {
                Vector2 pos0 = new Vector2(owner.transform.position.x, owner.transform.position.z);
                Vector2 pos1 = new Vector2(master.transform.position.x, master.transform.position.z);
                float dis = Vector2.Distance(pos0, pos1);
                if (dis > maxDis)
                {
                    state = State.Move;
                    owner.StopTo(master.transform.position);
                    if (owner.lod.IsPlayingAnim("stand"))
                        owner.PlayAnim("run", WrapMode.Loop);
                }
                else
                {
                    state = State.Stand;
                    owner.StopMove();

                    if (owner.lod.IsPlayingAnim("run"))
                        owner.PlayAnim("stand", WrapMode.Loop);
                }
            }
        }
    }
}